
package com.kugou.game.sdk.base;

import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.ui.widget.TipsLayout;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * 描述:列表fragment，封装了列表刷新，失败提示等功能
 * 
 * @author chenys
 * @since 2014-4-23 下午2:07:52
 */
public abstract class BaseListFragment<T> extends BaseSDKWorkerFragment implements
        OnScrollListener, OnItemClickListener {

    /**
     * 指定layout资源id
     * 
     * @return
     */
    protected abstract int findLayoutId();

    /**
     * 添加头部
     * 
     * @param listView
     */
    protected void addHeaderView(ListView listView) {
    }

    /**
     * 创建适配器
     * 
     * @return
     */
    protected abstract BaseListAdapter<T> createAdapter();

    /**
     * 加载数据，子类重写
     * 
     * @return
     */
    protected abstract ArrayList<T> loadDatas();

    /**
     * 列表点击回调
     * 
     * @param t
     */
    protected void onListItemClick(T t) {

    }

    /**
     * 设置是否延时加载
     * 
     * @param isDelayLoad
     */
    protected void setDelayLoad(boolean isDelayLoad) {
        mDelayLoad = isDelayLoad;
    }

    /**
     * 设置当所有数据加载完毕时是否移除footerView
     * 
     * @param isDelayLoad
     */
    protected void setRemoveFooterViewAfterAllDataLoaded(boolean remove) {
        mRemoveFooterViewAfterAllDataLoaded = remove;
    }

    /**
     * 获取页码
     * 
     * @return
     */
    protected int getPageIndex() {
        return mPageIndex;
    }

    protected Context mContext;

    protected ListView mListView;

    private View mFooterView;

    protected TipsLayout mTipsLayout;

    protected BaseListAdapter<T> mAdapter;

    protected int PAGE_SIZE = 30;

    private int mPageIndex = 0;

    // 数据是否已经全部加载完
    private boolean mHasLoadAllData;

    // 是否延迟加载,如果延迟加载的话，在方法startLoadData中开始触发加载
    private boolean mDelayLoad = false;

    private boolean mRemoveFooterViewAfterAllDataLoaded = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(findLayoutId(), null);
        mListView = (ListView) view.findViewById(Rx.id.kg_common_list);
        if (mListView == null) {
            throw new IllegalArgumentException("can not find R.id.kg_common_list.");
        }
        mTipsLayout = (TipsLayout) view.findViewById(Rx.id.kg_custom_tipslayout);
        if (mTipsLayout == null) {
            throw new IllegalArgumentException("can not find R.id.kg_custom_tipslayout.");
        }

        mListView.setOnScrollListener(this);
        mListView.setOnItemClickListener(this);
        addHeaderView(mListView);

        mFooterView = inflater.inflate(Rx.layout.kg_view_footer_loading, null);
        mFooterView.findViewById(Rx.id.kg_custom_loading_view).setVisibility(View.GONE);
        mFooterView.findViewById(Rx.id.kg_tv_loading_tips).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (getView().findViewById(Rx.id.kg_custom_loading_view).getVisibility() == View.VISIBLE) {
                            return;
                        }
                        if (mHasLoadAllData) {
                            return;
                        }
                        sendEmptyBackgroundMessage(MSG_BACK_LOAD_DATA);
                    }
                });

        mListView.addFooterView(mFooterView);

        mAdapter = createAdapter();
        mListView.setAdapter(mAdapter);

        mTipsLayout.setOnRefreshButtonClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sendEmptyBackgroundMessage(MSG_BACK_LOAD_DATA);
            }
        });

        if (!mDelayLoad) {
            sendEmptyBackgroundMessage(MSG_BACK_LOAD_DATA);
        }
        return view;
    }

    // 重新加载数据，页面索引清0
    public void reLoadData() {
        mHasLoadAllData = false;
        mPageIndex = 0;
        if (mAdapter != null) {
            mAdapter.clearDatas();
        }
        sendEmptyBackgroundMessage(MSG_BACK_LOAD_DATA);
    }

    private final static int STATE_LOADING = 0X01;

    private final static int STATE_LOAD_MORE = 0X02;

    private final static int STATE_LOAD_ALL_DATA = 0X03;

    // 设置footerView状态
    private void setFooterViewState(int state) {
        TextView textView = (TextView) mFooterView.findViewById(Rx.id.kg_tv_loading_tips);
        LoadingView loadingView = (LoadingView) mFooterView
                .findViewById(Rx.id.kg_custom_loading_view);
        if (state == STATE_LOADING) {
            // 显示正在加载
            textView.setText("正在加载...");
            loadingView.setVisibility(View.VISIBLE);
        } else if (state == STATE_LOAD_MORE) {
            // 显示加载更多
            textView.setText("加载更多");
            loadingView.setVisibility(View.GONE);
        } else if (state == STATE_LOAD_ALL_DATA) {
            // 显示数据全部加载
            textView.setText("已到达最底部");
            loadingView.setVisibility(View.GONE);
        }
    }

    public static final int MSG_UI_START_LOADING = 0x1000;

    public static final int MSG_UI_LOAD_SUCCESS = 0x1001;

    public static final int MSG_UI_LOAD_FAILE = 0x1002;

    public static final int MSG_UI_ALL_DATA_HAVE_LOADED = 0x1003;

    public static final int MSG_UI_NO_DATA = 0x1004;

    @Override
    public void handleUiMessage(Message msg) {
        super.handleUiMessage(msg);
        switch (msg.what) {
            case MSG_UI_START_LOADING:
                // 开始加载数据，显示loading
                if (mPageIndex == 1) {
                    mTipsLayout.show(TipsLayout.TYPE_LOADING);
                } else {
                    setFooterViewState(STATE_LOADING);
                    mTipsLayout.hide();
                }
                break;
            case MSG_UI_LOAD_SUCCESS:
                // 数据加载成功,且数据条数不为0
                if (msg.obj instanceof ArrayList<?>) {
                    ArrayList<T> datas = (ArrayList<T>) msg.obj;
                    mAdapter.addDatas(datas);
                    mAdapter.notifyDataSetChanged();
                }
                setFooterViewState(STATE_LOAD_MORE);
                mTipsLayout.hide();
                break;
            case MSG_UI_LOAD_FAILE:
                // 数据加载失败
                if (mPageIndex > 0) {
                    mPageIndex--;
                }
                if (mPageIndex != 0) {
                    setFooterViewState(STATE_LOAD_MORE);
                    mTipsLayout.hide();
                    showToast("数据加载失败");
                } else {
                    mTipsLayout.show(TipsLayout.TYPE_FAILE);
                }
                break;
            case MSG_UI_ALL_DATA_HAVE_LOADED:
                mHasLoadAllData = true;
                setFooterViewState(STATE_LOAD_ALL_DATA);
                if (mRemoveFooterViewAfterAllDataLoaded) {
                    mListView.removeFooterView(mFooterView);
                }
                // 数据不满一屏的时候，也不用显示
                if (mAdapter.getCount() < PAGE_SIZE) {
                    View view = mAdapter.getView(0, null, null);
                    int height = 0;
                    if (view != null) {
                        view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                                LayoutParams.WRAP_CONTENT));
                        view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                        height = view.getMeasuredHeight();
                        if (AppUtil.getDisplayScreenResolution(mContext).y > height
                                * mAdapter.getCount()) {
                            mListView.removeFooterView(mFooterView);
                        }
                    }

                }
                break;
            case MSG_UI_NO_DATA:
                // 数据加载成功,但数据条数为0
                if (mPageIndex > 0) {
                    mPageIndex--;
                }
                if (mPageIndex == 0) {
                    mTipsLayout.hide();
                }
                mHasLoadAllData = true;
                setFooterViewState(STATE_LOAD_ALL_DATA);
                if (mRemoveFooterViewAfterAllDataLoaded) {
                    mListView.removeFooterView(mFooterView);
                }
                break;
        }
    }

    private static final int MSG_BACK_LOAD_DATA = 0x2000;

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);
        switch (msg.what) {
            case MSG_BACK_LOAD_DATA:
                // 开始请求数据
                ++mPageIndex;
                sendEmptyUiMessage(MSG_UI_START_LOADING);
                ArrayList<T> datas = loadDatas();
                if (datas != null) {
                    if (datas.size() > 0 || mAdapter.getCount() > 0) {
                        Message message = obtainUiMessage();
                        message.what = MSG_UI_LOAD_SUCCESS;
                        message.obj = datas;
                        message.sendToTarget();
                        if (datas.size() < PAGE_SIZE) {
                            sendEmptyUiMessage(MSG_UI_ALL_DATA_HAVE_LOADED);
                        }
                    } else {
                        sendEmptyUiMessage(MSG_UI_NO_DATA);
                    }
                } else {
                    // apps为null表示加载数据失败
                    sendEmptyUiMessage(MSG_UI_LOAD_FAILE);
                }
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position > mListView.getHeaderViewsCount() - 1
                && position - mListView.getHeaderViewsCount() < mAdapter.getCount()) {
            T data = mAdapter.getItem(position - mListView.getHeaderViewsCount());
            onListItemClick(data);
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        View layoutLoading = getView().findViewById(Rx.id.kg_loading_layout);
        if (layoutLoading == null) {
            return;
        }
        // 滚动到底部
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
                || scrollState == OnScrollListener.SCROLL_STATE_FLING) {
            if (view.getLastVisiblePosition() >= (view.getCount() - 1)) {
                if (mHasLoadAllData) {
                    TextView tv = (TextView) mFooterView.findViewById(Rx.id.kg_tv_loading_tips);
                    tv.setText("全部加载完毕");
                    mFooterView.findViewById(Rx.id.kg_custom_loading_view).setVisibility(View.GONE);
                    return;
                }
                if (mFooterView.findViewById(Rx.id.kg_custom_loading_view).getVisibility() == View.VISIBLE) {
                    return;
                }
                mFooterView.findViewById(Rx.id.kg_custom_loading_view).setVisibility(View.VISIBLE);
                sendEmptyBackgroundMessage(MSG_BACK_LOAD_DATA);
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount) {
    }
}
